﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TruongVu.Business;
using TruongVu.Data;

namespace TruongVuWebsite.Admin
{
    public partial class NewsDetail : System.Web.UI.Page
    {
        private News _news = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            this._news = new News();
            if (this.IsPostBack)
            {
                return;
            }

            if (Request["ID"] != null)
            {
                New news = this._news.GetNewbyID(int.Parse(Request["ID"]));
                if (news != null)
                {
                    this.txtTitle.Text = news.Title;
                    this.txtContent.Value = news.Content;
                    this.DateTimeTextBox.Text = news.Date.ToShortDateString();
                    this.HighlightTextBox.Text = news.Highlight;
                    this.Image1.ImageUrl = Server.MapPath(news.Image);
                }
            }
            else
            {
                DateTimeTextBox.Text = DateTime.Now.ToShortDateString();
            }
        }

        protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
        {
            // create new tin tức
            if (Request["ID"] == null)
            {
                New news = new New();
                news.Date = DateTime.Now;
                news.Title = this.txtTitle.Text;
                news.Content = this.txtContent.Value;
                news.Highlight = this.HighlightTextBox.Text;
                news.Image =this.Image1.ImageUrl.Replace(Server.MapPath("~"), "~\\");
                this._news.InsertNews(news);
            }
            else
            {
                New news = new New();
                news.ID = int.Parse(Request["ID"]);
                DateTime dateTime = DateTime.Now;
                DateTime.TryParse(this.DateTimeTextBox.Text, out dateTime);
                news.Date = dateTime;
                news.Title = this.txtTitle.Text;
                news.Content = this.txtContent.Value;
                news.Highlight = this.HighlightTextBox.Text;
                news.Image = this.Image1 != null && this.Image1.ImageUrl != null ? this.Image1.ImageUrl.Replace(Server.MapPath("~"), "~\\") : string.Empty;
                this._news.UpdateNews(news);
            }

            Response.Redirect("NewsManagement.aspx");
        }

        protected void UploadButton_Click(object sender, EventArgs e)
        {
            if (FileUploadControl.HasFile)
            {
                string filename = System.IO.Path.GetFileName(FileUploadControl.FileName);
                FileUploadControl.SaveAs(Server.MapPath("~/UploadImages/") + filename);
                this.Image1.ImageUrl = Server.MapPath("~/UploadImages/") + filename;
            }
        }
    }
}